package cn.easyplatform.studio.web.action.MobileExport;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.mobileConf.*;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.FileUtil;
import cn.easyplatform.studio.utils.ImageUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.MobileConfVo;
import cn.easyplatform.studio.web.action.AbstractAction;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.zkoss.util.media.Media;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MobileAction extends AbstractAction {

    protected Textbox bundleTextbox;

    protected Textbox displayNameTextbox;

    protected Textbox versionTextbox;

    protected Textbox urlTextbox;

    protected Div iconDiv;

    protected Image iconImg;

    protected Button iconBtn;

    protected Div smallPortraitDiv;

    protected Image launchSmallPortraitImg;

    protected Button launchSmallPortraitBtn;

    protected Div smallLandscapeDiv;

    protected Image launchSmallLandscapeImg;

    protected Button launchSmallLandscapeBtn;

    protected Div bigPortraitDiv;

    protected Image launchBigPortraitImg;

    protected Button launchBigPortraitBtn;

    protected Div bigLandscapeDiv;

    protected Image launchBigLandscapeImg;

    protected Button launchBigLandscapeBtn;

    protected Button finishBtn;

    protected MobileConfVo vo;

    protected BufferedImage iconImage;

    protected String iconImageFormat;

    protected Boolean isNeedUpdateLocalIconImage = false;

    protected String iconImagePath;

    protected BufferedImage smallPortraitImage;

    protected String smallPortraitImageFormat;

    protected Boolean isNeedUpdateLocalSmallPortraitImage = false;

    protected String smallPortraitImagePath;

    protected BufferedImage smallLandscapeImage;

    protected String smallLandscapeImageFormat;

    protected Boolean isNeedUpdateLocalSmallLandscapeImage = false;

    protected String smallLandscapeImagePath;

    protected BufferedImage bigPortraitImage;

    protected String bigPortraitImageFormat;

    protected Boolean isNeedUpdateLocalBigPortraitImage = false;

    protected String bigPortraitImagePath;

    protected BufferedImage bigLandscapeImage;

    protected String bigLandscapeImageFormat;

    protected Boolean isNeedUpdateLocalBigLandscapeImage = false;

    protected String bigLandscapeImagePath;

    protected Window window;

    protected boolean isChangeContent = false;

    protected Button helpBtn;
    /**
     * @param workbench
     */
    public MobileAction(WorkbenchController workbench) {
        super(workbench);
    }

    @Override
    public void on() {
    }

    protected void setDefaultConf(String mobileType) {
        if (MobileConfVo.iOSCONF.equals(mobileType))
            vo = StudioApp.execute(new GetiOSConfCmd());
        else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
            vo = StudioApp.execute(new GetAndroidConfCmd());
        else if (MobileConfVo.WXCONF.equals(mobileType))
            vo = StudioApp.execute(new GetWXConfCmd());
        if (vo != null) {
            bundleTextbox.setValue(vo.getBundleId());
            displayNameTextbox.setValue(vo.getDisplayName());
            if (versionTextbox != null)
                versionTextbox.setValue(vo.getMobileVersion());
            urlTextbox.setValue(vo.getUrl());

        if (vo.getIcon() != null)
            {
                File iconFile = new File(StudioApp.getServletContext().getRealPath(vo.getIcon()));
                if (iconFile != null && iconFile.exists()) {
                    try {
                        iconImageFormat = iconFile.getPath().substring(iconFile.getPath().length()-3,Integer.parseInt(iconFile.getPath().length()+""));
                        iconImage = ImageIO.read(iconFile);
                        iconImagePath = vo.getIcon();

                        String smallLandscapeFileStr = null;
                        String bigLandscapeFileStr = null;
                        String smallPortraitFileStr = null;
                        String bigPortraitFileStr = null;
                        if (MobileConfVo.iOSCONF.equals(mobileType))
                        {
                            JSONObject object = JSON.parseObject(vo.getLaunch());
                            smallLandscapeFileStr = object.getString("smallLandscapeLaunchImage");
                            bigLandscapeFileStr = object.getString("bigLandscapeLaunchImage");
                            smallPortraitFileStr = object.getString("smallPortraitLaunchImage");
                            bigPortraitFileStr = object.getString("bigPortraitLaunchImage");
                        }
                        else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
                        {
                            bigPortraitFileStr = vo.getLaunch();
                        }

                        if (smallPortraitFileStr != null)
                        {
                            File smallPortraitFile = new File(StudioApp.getServletContext().getRealPath(smallPortraitFileStr));
                            if (smallPortraitFile.exists()) {
                                smallPortraitImage = ImageIO.read(smallPortraitFile);
                                smallPortraitImagePath = smallPortraitFileStr;
                                smallPortraitImageFormat = smallPortraitFile.getPath().substring(smallPortraitFile.getPath().length()-3,Integer.parseInt(smallPortraitFile.getPath().length()+""));
                            }
                            else
                            {
                                isNeedUpdateLocalSmallPortraitImage = true;
                            }
                        }

                        if (smallLandscapeFileStr != null)
                        {
                            File smallLandscapeFile = new File(StudioApp.getServletContext().getRealPath(smallLandscapeFileStr));
                            if (smallLandscapeFile.exists()) {
                                smallLandscapeImage = ImageIO.read(smallLandscapeFile);
                                smallLandscapeImagePath = smallLandscapeFileStr;
                                smallLandscapeImageFormat = smallLandscapeFile.getPath().substring(smallLandscapeFile.getPath().length()-3,Integer.parseInt(smallLandscapeFile.getPath().length()+""));
                            }
                            else
                            {
                                isNeedUpdateLocalSmallLandscapeImage = true;
                            }
                        }

                        if (bigLandscapeFileStr != null)
                        {
                            File bigLandscapeFile = new File(StudioApp.getServletContext().getRealPath(bigLandscapeFileStr));
                            if (bigLandscapeFile.exists()) {
                                bigLandscapeImage = ImageIO.read(bigLandscapeFile);
                                bigLandscapeImagePath = bigLandscapeFileStr;
                                bigLandscapeImageFormat = bigLandscapeFile.getPath().substring(bigLandscapeFile.getPath().length()-3,Integer.parseInt(bigLandscapeFile.getPath().length()+""));
                            }
                            else {
                                isNeedUpdateLocalBigLandscapeImage = true;
                            }
                        }
                        if (bigPortraitFileStr != null)
                        {
                            File bigPortraitFile = new File(StudioApp.getServletContext().getRealPath(bigPortraitFileStr));
                            if (bigPortraitFile.exists()) {
                                bigPortraitImage = ImageIO.read(bigPortraitFile);
                                bigPortraitImagePath = bigPortraitFileStr;
                                bigPortraitImageFormat = bigPortraitFile.getPath().substring(bigPortraitFile.getPath().length()-3,Integer.parseInt(bigPortraitFile.getPath().length()+""));
                            }
                            else {
                                isNeedUpdateLocalBigPortraitImage = true;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    isNeedUpdateLocalIconImage = true;
                }

                showCorrectImg();
            }

        }
    }

    private void showCorrectImg()
    {
        if (iconImage != null && iconImg != null)
        {
            iconImg.setVisible(true);
            iconDiv.setVisible(false);
            iconImg.setContent(iconImage);
        }
        if (smallLandscapeImage != null && launchSmallLandscapeImg != null)
        {
            launchSmallLandscapeImg.setVisible(true);
            smallLandscapeDiv.setVisible(false);
            launchSmallLandscapeImg.setContent(smallLandscapeImage);
        }
        if (smallPortraitImage != null && launchSmallPortraitImg != null)
        {
            launchSmallPortraitImg.setVisible(true);
            smallPortraitDiv.setVisible(false);
            launchSmallPortraitImg.setContent(smallPortraitImage);
        }
        if (bigLandscapeImage != null && launchBigLandscapeImg != null)
        {
            launchBigLandscapeImg.setVisible(true);
            bigLandscapeDiv.setVisible(false);
            launchBigLandscapeImg.setContent(bigLandscapeImage);
        }
        if (bigPortraitImage != null && launchBigPortraitImg != null)
        {
            launchBigPortraitImg.setVisible(true);
            bigPortraitDiv.setVisible(false);
            launchBigPortraitImg.setContent(bigPortraitImage);
        }
    }

    protected void verifyImage(Event event) {
        UploadEvent uploadEvent = (UploadEvent) event;
        Component c = uploadEvent.getTarget();
        Media media = uploadEvent.getMedia();

        if (media instanceof org.zkoss.image.Image) {
            //判断图片格式
            boolean isCorrectFormat = "png".equals(media.getFormat()) || "jpg".equals(media.getFormat()) || "jpeg".equals(media.getFormat());

            if (isCorrectFormat) {
                org.zkoss.image.Image img = (org.zkoss.image.Image) media;
                BufferedImage bufferedImage = null;
                InputStream inputStream = media.getStreamData();
                try {
                    bufferedImage = ImageIO.read(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //透明度
                int rgb = bufferedImage.getRGB(0, 0);
                if (rgb == 0) {
                    WebUtils.showError(Labels.getLabel("mobileExport.launch.upload.error"));
                    return;
                }
                int alpha = (0xff & (rgb >> 24));
                boolean isTransparent = alpha != 255;
                boolean isCorrectImg = false;

                if (c == iconBtn && new Double(img.getWidth()) == 1024.00 && new Double(img.getHeight()) == 1024.00 && isCorrectFormat && (!isTransparent)) {
                    isCorrectImg = true;
                    iconImage = bufferedImage;
                    iconImageFormat = media.getFormat();
                    isNeedUpdateLocalIconImage = true;
                } else if (c == launchSmallPortraitBtn && new Double(img.getWidth()) == 1242.00 && new Double(img.getHeight()) == 2208.00 && isCorrectFormat && (!isTransparent)) {
                    isCorrectImg = true;
                    smallPortraitImage = bufferedImage;
                    smallPortraitImageFormat = media.getFormat();
                    isNeedUpdateLocalSmallPortraitImage = true;
                } else if (c == launchBigPortraitBtn && new Double(img.getWidth()) == 1242.00 && new Double(img.getHeight()) == 2688.00 && isCorrectFormat && (!isTransparent)) {
                    isCorrectImg = true;
                    bigPortraitImage = bufferedImage;
                    bigPortraitImageFormat = media.getFormat();
                    isNeedUpdateLocalBigPortraitImage = true;
                }else if (c == launchSmallLandscapeBtn && new Double(img.getWidth()) == 2208.00 && new Double(img.getHeight()) == 1242.00 && isCorrectFormat && (!isTransparent)) {
                    isCorrectImg = true;
                    smallLandscapeImage = bufferedImage;
                    smallLandscapeImageFormat = media.getFormat();
                    isNeedUpdateLocalSmallLandscapeImage = true;
                } else if (c == launchBigLandscapeBtn && new Double(img.getWidth()) == 2688.00 && new Double(img.getHeight()) == 1242.00 && isCorrectFormat && (!isTransparent)) {
                    isCorrectImg = true;
                    bigLandscapeImage = bufferedImage;
                    bigLandscapeImageFormat = media.getFormat();
                    isNeedUpdateLocalBigLandscapeImage = true;
                }

                if (isCorrectImg) {
                    showCorrectImg();
                } else {
                    WebUtils.showError(Labels.getLabel("mobileExport.launch.upload.error"));
                }
            } else {
                WebUtils.showError(Labels.getLabel("mobileExport.launch.upload.error"));
            }
        } else {
            WebUtils.showError(Labels.getLabel("mobileExport.launch.upload.error"));
        }
    }

    protected boolean uploaToDatabase(String mobileType)
    {
        boolean isEmptyLaunch = false;
        boolean isEmptyDisplayName = false;
        if (MobileConfVo.iOSCONF.equals(mobileType))
        {
            if (launchSmallLandscapeImg == null || launchBigLandscapeImg == null || launchSmallPortraitImg == null || launchBigPortraitImg == null)
            {
                isEmptyLaunch = true;
            }
            if (Strings.isBlank(displayNameTextbox.getValue()))
            {
                isEmptyDisplayName = true;
            }
        }
        else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
        {
            if (launchBigPortraitImg == null)
            {
                isEmptyLaunch = true;
            }
            if (Strings.isBlank(displayNameTextbox.getValue()))
            {
                isEmptyDisplayName = true;
            }
        }
        else if (MobileConfVo.WXCONF.equals(mobileType))
        {
            if (validator("^\\s*[a-zA-Z][a-zA-Z0-9]*s*$",displayNameTextbox.getValue()) == false)
            {
                isEmptyDisplayName = true;
            }

        }

        if (Strings.isBlank(bundleTextbox.getValue()))
            WebUtils.showError(Labels.getLabel("message.no.empty",new String[]{Labels.getLabel("mobileExport.bundle")}));
        else if (isEmptyDisplayName)
            WebUtils.showError(Labels.getLabel("message.no.empty",new String[]{Labels.getLabel("mobileExport.displayName")}));
        else if ((!MobileConfVo.WXCONF.equals(mobileType)) && Strings.isBlank(versionTextbox.getValue()))
            WebUtils.showError(Labels.getLabel("message.no.empty",new String[]{Labels.getLabel("mobileExport.version")}));
        else if ((!MobileConfVo.WXCONF.equals(mobileType)) && iconImage == null )
            WebUtils.showError(Labels.getLabel("message.no.empty",new String[]{Labels.getLabel("mobileExport.icon")}));
        else if (isEmptyLaunch)
            WebUtils.showError(Labels.getLabel("message.no.empty", new String[]{Labels.getLabel("mobileExport.launch")}));
        else if ((!MobileConfVo.WXCONF.equals(mobileType)) && validator("^\\s*(([0-9]|[a-zA-z])+\\.)+([0-9]|[a-zA-z])+s*$",bundleTextbox.getValue()) == false)
            WebUtils.showError(Labels.getLabel("mobileExport.input.error",new String[]{Labels.getLabel("mobileExport.bundle")}));
        else if ((!MobileConfVo.WXCONF.equals(mobileType)) && validator("^\\s*(([1-9]\\d*|0)\\.)+([1-9]\\d*|0)s*$",versionTextbox.getValue()) == false)
            WebUtils.showError(Labels.getLabel("mobileExport.input.error",new String[]{Labels.getLabel("mobileExport.version")}));
        else if ((!MobileConfVo.WXCONF.equals(mobileType)) && validator("^\\s*[a-zA-z]+://[^\\s]*s*$",urlTextbox.getValue()) == false)
            WebUtils.showError(Labels.getLabel("mobileExport.input.error",new String[]{Labels.getLabel("mobileExport.url")}));
        else
        {
            String launcContent = null;
            String versionContent = null;
            if (!MobileConfVo.WXCONF.equals(mobileType))
            {
                String type = null;
                if (MobileConfVo.iOSCONF.equals(mobileType))
                {
                    type = "iOS";
                }
                else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
                {
                    type = "Android";
                }

                String mainDir = FileUtil.getCachePath();

                if (isNeedUpdateLocalIconImage == true)
                    iconImagePath = mainDir + Contexts.getProject().getName() + "/" + type + "/" + "1024.png";
                if (isNeedUpdateLocalSmallPortraitImage == true)
                    smallPortraitImagePath = mainDir + Contexts.getProject().getName() + "/" + type + "/" + "12422208.png";
                if (isNeedUpdateLocalBigPortraitImage == true)
                    bigPortraitImagePath = mainDir + Contexts.getProject().getName() + "/" + type + "/" + "12422688.png";
                if (isNeedUpdateLocalSmallLandscapeImage == true)
                    smallLandscapeImagePath = mainDir + Contexts.getProject().getName() + "/" + type + "/" + "22081242.png";
                if (isNeedUpdateLocalBigLandscapeImage == true)
                    bigLandscapeImagePath = mainDir + Contexts.getProject().getName() + "/" + type + "/" + "26881242.png";

                if (isNeedUpdateLocalBigLandscapeImage == true || isNeedUpdateLocalIconImage == true || isNeedUpdateLocalSmallLandscapeImage == true || isNeedUpdateLocalBigPortraitImage == true || isNeedUpdateLocalSmallPortraitImage)
                {
                    FileUtil.createPath(StudioApp.getServletContext().getRealPath(mainDir +
                            Contexts.getProject().getName() + "/" + type + "/"));
                    try {
                        if (isNeedUpdateLocalIconImage == true) {
                            ImageUtil.resizeAndWriteImage(iconImage,
                                    StudioApp.getServletContext().getRealPath(iconImagePath), 1024,
                                    1024, iconImageFormat);
                        }
                        if (isNeedUpdateLocalSmallPortraitImage == true) {
                            ImageUtil.resizeAndWriteImage(smallPortraitImage,
                                    StudioApp.getServletContext().getRealPath(smallPortraitImagePath), 1242,
                                    2208, smallPortraitImageFormat);
                        }
                        if (isNeedUpdateLocalBigPortraitImage == true) {
                            ImageUtil.resizeAndWriteImage(bigPortraitImage,
                                    StudioApp.getServletContext().getRealPath(bigPortraitImagePath), 1242,
                                    2688, bigPortraitImageFormat);
                        }
                        if (isNeedUpdateLocalSmallLandscapeImage == true) {
                            ImageUtil.resizeAndWriteImage(smallLandscapeImage,
                                    StudioApp.getServletContext().getRealPath(smallLandscapeImagePath),
                                    2208, 1242, smallLandscapeImageFormat);
                        }
                        if (isNeedUpdateLocalBigLandscapeImage == true) {
                            ImageUtil.resizeAndWriteImage(bigLandscapeImage,
                                    StudioApp.getServletContext().getRealPath(bigLandscapeImagePath), 2688,
                                    1242, bigLandscapeImageFormat);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                if (MobileConfVo.iOSCONF.equals(mobileType))
                {
                    JSONObject json = new JSONObject();
                    json.put("smallPortraitLaunchImage",smallPortraitImagePath);
                    json.put("bigPortraitLaunchImage",bigPortraitImagePath);
                    json.put("smallLandscapeLaunchImage",smallLandscapeImagePath);
                    json.put("bigLandscapeLaunchImage",bigLandscapeImagePath);
                    launcContent = json.toJSONString();
                }
                else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
                {
                    launcContent = bigPortraitImagePath;
                }

                versionContent = versionTextbox.getValue();
            }

            boolean isAdd = false;
            if (vo == null) {
                isAdd = true;
                vo = new MobileConfVo( -1, null, mobileType, bundleTextbox.getValue(), displayNameTextbox.getValue(),
                        versionContent, iconImagePath, launcContent, urlTextbox.getValue(), null, null,
                        null, null);
            } else {
                vo.setConfType(mobileType);
                vo.setBundleId(bundleTextbox.getValue());
                vo.setDisplayName(displayNameTextbox.getValue());
                vo.setMobileVersion(versionContent);
                vo.setIcon(iconImagePath);
                vo.setLaunch(launcContent);
                vo.setUrl(urlTextbox.getValue());
            }

            if (isChangeContent) {
                if (isAdd) {
                    if (MobileConfVo.iOSCONF.equals(mobileType))
                        StudioApp.execute(new SetiOSConfCmd(vo));
                    else if (MobileConfVo.ANDROIDCONF.equals(mobileType))
                        StudioApp.execute(new SetAndroidConfCmd(vo));
                    else if (MobileConfVo.WXCONF.equals(mobileType))
                        StudioApp.execute(new SetWXConfCmd(vo));
                } else {
                    StudioApp.execute(new UpdateMobileConfCmd(vo));
                }

            }
            return true;
        }
        return false;
    }

    private boolean validator(String regEx,String content)
    {
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(content);
        boolean rs = matcher.matches();
        return rs;
    }
}
